import sys, xmlrpclib, logging, math
from prepconf import loadhosts

log = logging.getLogger('prep-conf')

def latlon(hostname):
    api_server = xmlrpclib.ServerProxy('https://www.planet-lab.org/PLCAPI/')
    auth = {}
    auth['AuthMethod'] = "anonymous"
    auth['Role'] = "user"

    log.debug("query: "+str(hostname))
    query = api_server.GetNodes(auth, {'hostname': hostname}, ['site_id'])
    site_id = query[0]['site_id']
    site_info = api_server.GetSites(auth, {'site_id': site_id}, ['site_id', 'name', 'url', 'latitude', 'longitude', 'login_base'])
    log.debug("siteinfo: "+str(site_info))
    log.debug("siteinfo[0]: "+str(site_info[0]))
    return( site_info[0]['latitude'], site_info[0]['longitude'] )

def writeLatLon():
    hosts = loadhosts()
    f = open("hostlatlon.txt", "w")
    for host in hosts:
        (lat,lon) = latlon(host)
        f.write(host + ", "+str(lat)+", "+str(lon)+"\n")
    f.close()    

def writeCosts():
    latlonf = open("hostlatlon.txt")
    llcache = {}
    for line in latlonf:
        tokens = line.strip().split(",")
        llcache[tokens[0]] = ( float(tokens[1]), float(tokens[2]) )
    latlonf.close()

    costf = open("hostcosts.txt", "w")
    hosts = llcache.keys()
    for host in hosts:
        for host2 in hosts:
            if host==host2:
                continue
            cost = math.sqrt( math.pow( llcache[host][0] - llcache[host2][0], 2) + 
                              math.pow( llcache[host][1] - llcache[host2][1], 2) )
            cost = int(0.5 + cost)
            costf.write("cost,"+str(host)+","+str(host2)+" = "+str(cost) + "\n")
    costf.close()

if __name__=="__main__":
    logging.basicConfig(level=logging.DEBUG)
    try:
        open("hostlatlon.txt")
    except IOError:
        log.info("latlon missing; creating it")
        writeLatLon()
    try:
        open("hostcosts.txt")
    except IOError:
        log.info("hostcosts missing; creating it")
        writeCosts()
        
    log.info("all done")
